/* Copyright 2008 Bas van den Berg
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef MUDOBJECTTASK_H
#define MUDOBJECTTASK_H

#include "TaskQueue.h"
#include "MudObject.h"

namespace Chronos {

template <typename T>
class MudObjectTask : public Task, public MudObjectListener {
public:
    MudObjectTask(T& object_)
        : object(&object_)
    {
        object->addListener(*this);
    }
    virtual ~MudObjectTask() {
        if (object != 0) object->removeListener(*this);
    }
    virtual unsigned int run() {
        if (object == 0) return 0;
        return run2();
    }
    virtual unsigned int run2() = 0;
    virtual bool handleObjectEvent(MudObject&, MudObjectEvent event) {
        switch(event) {
        case OBJECT_DESTRUCTION:
        case MUDMOBILE_DEATH:
            object = 0;
            return false;
        default:
            break;
        }
        return true;
    }
protected:
    T* object;
};


template <typename T>
class MudObjectFuncTask : public MudObjectTask<T> {
public:
    typedef unsigned int (T::*Function)();
    MudObjectFuncTask(T& object_, Function func_)
        : MudObjectTask<T>(object_)
        , func(func_)
    {}
    virtual unsigned int run2() {
        return (MudObjectTask<T>::object->*func)();
    }
private:
    Function func;
};

}

#endif

